package cn.tedu.dbinit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbInitApplication {

	public static void main(String[] args) {
		SpringApplication.run(DbInitApplication.class, args);
	}

	@Autowired
	private DataSource dataSource;

	/**
	 * spring 的执行流程：
	 * 包扫描创建 所有的实例，完成所有的依赖注入，@PostConstruct
	 */
	@PostConstruct
	public void init() throws SQLException {

		exec("sql/account.sql");
		exec("sql/order.sql");
		exec("sql/seata-server.sql");
		exec("sql/storage.sql");

	}

	private void exec(String s) throws SQLException {

		ClassPathResource cpr = new ClassPathResource(s, DbInitApplication.class.getClassLoader());
		// 处理中文编码
		EncodedResource resource = new EncodedResource(cpr, "utf-8");

		ScriptUtils.executeSqlScript(dataSource.getConnection(),resource);

	}

}
